<?php
namespace catchAdmin\registration\service;

use app\common\lib\ZhyxMongo;
use app\common\model\Follow as FollowModel;
use app\common\model\PatientInfo as InfoModel;

class StatisticsService
{
    /**
     * 随访任务详细统计
     * @param string $task_id
     * @return array
     */
    public function TaskDetailedStatistics(string $task_id): array
    {
        return  (new FollowModel())->getTaskDetailsStatistics($task_id);
    }

    /**
     * 随访任务图形统计
     * @param string $task_id
     * @return array
     */
    public function TaskDetailedChartStatistics(string $task_id): array
    {
        $list = (new FollowModel())->getTaskDetailsChartStatistics($task_id);

        $list['sms_lose_num'] = 0;
        $list['wechat_num'] = 0;
        $list['wechat_done_num'] = 0;
        $list['wechat_reply_num'] = 0;
        $list['wechat_noreply_num'] = 0;
        $list['wechat_lose_num'] = 0;
        $list['outpatient'] = 0;
        $list['inpatient'] = 0;
        return $list;
    }

    /**
     * 失访患者统计图
     * @return array
     */
    public function LostStatisticsChart(): array
    {
        #随访患者统计
        //未失访
        $pipLine = [['$match' => ['is_in_hospital' => 2, 'lost_access' => ['$ne' => 1], '$and' => [['presentTelphone' => ['$exists' => true]], ['$or' => [['presentTelphone' => ['$ne' => null]], ['presentTelphone' => ['$ne' => '']]]]]]], ['$count' => 'num']];
        $notLost = ZhyxMongo::getInstance()->setCollection('patient_info')->aggregate($pipLine);
        $notLost = iterator_to_array($notLost);

        //失访
        $lostNum = (new InfoModel())->where('lost_access', 1)->count();

        #失访患者统计
        $lostPipLine = [['$match' => ['lost_access' => 1, 'lost_access_result_code' => ['$in' => [8, 10, 16]]]], ['$group' => ['_id' => null, 'empty_count' => ['$sum' => ['$cond' => [['$eq' => ['$lost_access_result_code', 16]], 1, 0]]], 'wrong_count' => ['$sum' => ['$cond' => [['$eq' => ['$lost_access_result_code', 10]], 1, 0]]], 'refuse_count' => ['$sum' => ['$cond' => [['$eq' => ['$lost_access_result_code', 8]], 1, 0]]]]], ['$project' => ['_id' => false, 'empty_count' => ['$ifNull' => ['$empty_count', 0]], 'wrong_count' => ['$ifNull' => ['$wrong_count', 0]], 'refuse_count' => ['$ifNull' => ['$refuse_count', 0]]]]];
        $lostPatient = ZhyxMongo::getInstance()->setCollection('patient_info')->aggregate($lostPipLine);
        $lostPatient= iterator_to_array($lostPatient);

        return [
            'followPatient' => [
                'notLostNum' => $notLost[0]['num']??0,//未失访患者
                'lostNum' => $lostNum//失访患者
            ],
            'lostPatient' => [
                'emptyNum' => $lostPatient[0]['empty_count']??0,//错号
                'wrongNum' => $lostPatient[0]['wrong_count']??0,//空号
                'refuseNum' => $lostPatient[0]['refuse_count']??0//拒绝随访
            ]
        ];
    }
}